package com.shkco.xbjcc.service.impl;

import com.shkco.result.PageList;
import com.shkco.xbjcc.config.HighlightResultMapper;
import com.shkco.xbjcc.doc.CourseDoc;
import com.shkco.xbjcc.dto.CourseEsDto;
import com.shkco.xbjcc.repository.CourseEsRepository;
import com.shkco.xbjcc.result.EsAggrPageList;
import com.shkco.xbjcc.service.ISearchService;
import com.shkco.xbjcc.vo.AggrTermsBucketVo;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements ISearchService {

    @Autowired
    private CourseEsRepository courseEsRepository;

    @Override
    public void saveSearch(CourseDoc courseDoc) {
        courseEsRepository.save(courseDoc);
    }

    @Override
    public void delSearch(Long id) {
        courseEsRepository.deleteById(id);
    }

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    @Override
    public PageList<CourseDoc> search(CourseEsDto courseEsDto) {
        Long courseTypeId = courseEsDto.getCourseTypeId();
        String gradeName = courseEsDto.getGradeName();
        String keyword = courseEsDto.getKeyword();
        String sortField = courseEsDto.getSortField();
        String chargeName = courseEsDto.getChargeName();
        Double priceMin = courseEsDto.getPriceMin();
        Double priceMax = courseEsDto.getPriceMax();
        String sortType = courseEsDto.getSortType();
        Integer page = courseEsDto.getPage();
        Integer rows = courseEsDto.getRows();

        HighlightResultMapper highlightResultMapper = new HighlightResultMapper();

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 判断keyword是否有值
        if (!StringUtils.isEmpty(keyword)){
            boolQuery.must(QueryBuilders.matchQuery("name",keyword));
        }
        // 判断courseTypeId是否不为null
        if (courseTypeId != null){
            boolQuery.filter(QueryBuilders.termQuery("courseTypeId",courseTypeId));
        }
        // 判断gradeName是否有值
        if (!StringUtils.isEmpty(gradeName)){
            boolQuery.must(QueryBuilders.matchQuery("gradeName",gradeName));
        }
        // 判断chargeName是否有值
        if (!StringUtils.isEmpty(chargeName)){
            boolQuery.must(QueryBuilders.matchQuery("charge",chargeName));
        }
        // 判断priceMin是否不为null
        if (priceMin != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(priceMin));
        }
        // 判断priceMax是否不为null
        if (priceMax != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(priceMax));
        }
        // 判断排序字段是否有值
        if (!StringUtils.isEmpty(sortField) && !StringUtils.isEmpty(sortType)) {
            SortOrder sortOrder = "asc".equalsIgnoreCase(sortType) ? SortOrder.ASC : SortOrder.DESC;
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(sortField).order(sortOrder));
        }
        nativeSearchQueryBuilder.withQuery(boolQuery);
        // 设置分页条件
        nativeSearchQueryBuilder.withPageable(PageRequest.of(page - 1,rows));
        // 设置高亮
        nativeSearchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("name").preTags("<span style='color:red'>").postTags("</span>"));
        // 设置聚合
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("gradeNameTermsAgg").field("gradeName"));
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("chargeNameTermsAgg").field("charge"));



        NativeSearchQuery build = nativeSearchQueryBuilder.build();
//        Page<CourseDoc> search = courseEsRepository.search(build);
        AggregatedPage<CourseDoc> courseDocs = elasticsearchRestTemplate.queryForPage(build, CourseDoc.class, highlightResultMapper);

        Aggregations aggregations = courseDocs.getAggregations();

        Map<String, List<AggrTermsBucketVo>> aggrsMap = new HashMap<>();

        aggregations.asMap().entrySet().forEach(e->{
            List<AggrTermsBucketVo> aggrTermsBucketVos = new ArrayList<>();
            String key = e.getKey();
            ParsedStringTerms parsedStringTerms = (ParsedStringTerms) e.getValue();
            parsedStringTerms.getBuckets().forEach(p->{
                AggrTermsBucketVo aggrTermsBucketVo = new AggrTermsBucketVo();
                String keyAsString = p.getKeyAsString();
                long docCount = p.getDocCount();
                aggrTermsBucketVo.setKey(keyAsString);
                aggrTermsBucketVo.setDocCount(docCount);
                aggrTermsBucketVos.add(aggrTermsBucketVo);
            });
            aggrsMap.put(key, aggrTermsBucketVos);
        });

        // 返回分页数据
        return new EsAggrPageList<>(courseDocs.getTotalElements(), courseDocs.getContent(), aggrsMap);
    }

}
